<template>
    <div class="app-container usercenter">
        <van-nav-bar title="我的"></van-nav-bar>
        <div class="my-container">
            <div class="userinfo">
                <div class="avatar" @click="actionShow = true">
                    <img :src="headimg" alt="">
                    <!-- <van-image round :src="headimg" /> -->
                </div>
                <div class="nickname">
                    <span class="nickname-text">{{ nickName }}</span>
                    <!-- <span class="button-primary">{{ VIP > 0 ? 'VIP' : '普通用户'}}</span> -->
                </div>

            </div>
            <!-- 会员卡片 -->
            <vip-card :userInfo="info"></vip-card>
            <div class="user-group group-container">
                <van-cell-group>
                    <!-- <van-cell title="开通会员" icon="shopping-cart-o" is-link @click="$router.push('/setting/vipcenter')" /> -->
                    <van-cell :title="info.vip ? '我的会员' : '开通会员'" icon="shopping-cart-o" is-link @click="$router.push('/setting/vipcenter')" />
                    <van-cell title="我的策略" icon="guide-o" is-link @click="$router.push('/setting')" />
                    <van-cell title="推送设置" icon="bullhorn-o" :value="pushStateDesc" is-link @click="$router.push('/setting')" />
                    <van-cell title="代理计划" is-link @click="$router.push('/invite')" icon="add-o">
                    </van-cell>
                    <van-cell title="招募" is-link @click="$router.push({
                        name: 'InviteWeex',
                        query: {
                            type: 'inner'
                        }
                    })" icon="add-o">
                    </van-cell>
                    <van-cell title="加盟" icon="add-o" is-link @click="$router.push('/setting/join')" />
                    <van-cell title="历史战绩" is-link @click="handleOpenHistory" icon="browsing-history-o">
                    </van-cell>
                    <van-cell title="联系我们" icon="service-o" is-link @click="$router.push('/setting/kefu')" />
                    
                    <van-cell title="修改密码" is-link @click="$router.push('/setting/account-safe')" icon="shield-o">
                    </van-cell>
                    <van-cell title="安全退出" icon="peer-pay" is-link @click="onLogout(false)">
                    </van-cell>
                </van-cell-group>
            </div>
            <van-action-sheet v-model:show="actionShow" :actions="actions" @select="onActionSelect" cancel-text="取消"
                close-on-click-action />
            <van-dialog v-model:show="showNickDialog" :show-confirm-button="false" close-on-click-overlay>
                <div class="common-dialog">
                    <h3>修改昵称</h3>
                    <div class="common-dialog-content">
                        <van-field v-model="newnick" name="newnick" placeholder="请输入昵称" maxlength="20"></van-field>
                    </div>
                    <div style="margin: 44px 44px 16px">
                        <van-button block type="primary" :loading="loading" @click="saveNickName">提交</van-button>
                    </div>
                </div>
            </van-dialog>
            <van-action-sheet v-model:show="showPicker" title="周期推送设置" @open="getTimeCheckList">
                <div class="dialog-set">
                    <van-row>
                        <van-col span="8" v-for="item in columns" :key="item.value"  style="margin-bottom: 20px;">
                            <van-checkbox shape="square" v-model="item.select">{{ item.text
                            }}</van-checkbox>
                        </van-col>
                    </van-row>
                    <div class="dialog-footer">
                        <van-button class="dialog-save" size="small" type="primary"  @click="handleSaveTime">保存</van-button>
                    </div>
                    
                </div>
            </van-action-sheet>
        </div>

    </div>
</template>

<script>
import { utilsMixin } from '@/mixin/utils'
import { mapState, mapActions } from 'pinia'
import { useUserStore } from '@/store/user'
import { logout } from '@/api/login'
import { saveNickName, postPushState, putPushStateBatch, getPushState } from '@/api/user'
import { getMyInfo } from '@/api/home'
import { showConfirmDialog, showToast, showNotify } from 'vant'
import defaultHead from '@/assets/default.png'
import VipCard from '@/components/vip/index';
// import { getWxAppInfo } from '@/api/home'

export default {
    name: 'UserCenter',
    mixins: [utilsMixin],
    components: {
        VipCard
    },
    data() {
        return {
            showPicker: false,
            info: {},
            loading: false,
            actionShow: false,
            newnick: '',
            showNickDialog: false,
            pushState: '',
            align: 'start',
            columns: [
                { text: '15分钟', value: '2', select: false },
                { text: '30分钟', value: '3', select: false },
                { text: '1小时', value: '4', select: false },
                { text: '2小时', value: '7', select: false },
                { text: '4小时', value: '5', select: false },
                { text: '6小时', value: '8', select: false },
                { text: '12小时', value: '9', select: false },
                { text: '日线', value: '6', select: false },
            ],
            actions: [
                { name: '上传头像' },
                { name: '修改昵称' },
            ]
        }
    },
    created() {
        this.init();
        
    },
    methods: {
        ...mapActions(useUserStore, ['fedLogOut', 'setNickName']),
        // getStrategyName() {
        //     let name = [];
        //     this.strategyAllList.forEach(item => {
        //         if (this.info.subStrategyIds.includes(item.id)) {
        //             name.push(item.strategyName);
        //         }
        //     });
        //     return name.join(',')
        // },
        init() {
            getMyInfo().then(res => {
                if (res.code !== 20000) return;
                
                this.info = res.data;
                this.pushState = res.data.pushState
                if (!this.pushState) {
                    this.pushState = 'YES'
                }
            })

            // if (!this.wxOpenId) {
            //     getWxAppInfo().then(response => {
            //         if (response.success && response.data != null) {
            //             const data = response.data
            //             const appid = data.appId
            //             const host = location.href.split('#')[0] + 'wx/redirect/' + appid
            //             const url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURIComponent(host) + '&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
            //             location.href = url
            //         }
            //     })
            // }
           
        },
        getTimeCheckList() {
            getPushState().then((res) => {
                if (res.data) {
                    const data = res.data.split(',')

                    this.columns.forEach(item => {
                        if (data.includes(item.value)) {
                            item.select = true;
                        } else {
                            item.select = false;
                        }
                    })
                }

            })
        },
        handleSaveTime() {
            const selectsStr = this.columns.filter(item => item.select).map(m => m.value).join(',');
            putPushStateBatch(selectsStr).then((res) => {
                if (res.code === 20000) {
                    showToast('周期推送配置修改成功')
                    this.showPicker = false
                } 
            }).catch(() => { 
            })
        },
        onLogout(mc) {
            if (!mc) {
                showConfirmDialog({
                    message: '确认退出吗？',
                }).then(() => {
                    this.onLogout(true)
                })
                return
            }
            logout().then(() => {
                this.fedLogOut().then(() => {
                    location.reload()
                })
            }).catch(err => {
                console.log(err)
            })
        },
        handleOpenHistory() {
            // showToast('敬请期待')
            //  window.open('https://weibo.com/u/page/follow/6703018096');

            this.$router.push({
                name: 'HistorySilent',
                query: {
                    type: 'inner'
                }
            });
        },
        onActionSelect(item, index) {
            this.actionShow = false
            if (index == 1) {
                this.newnick = ''
                this.showNickDialog = true
            } else if (index == 0) {
                this.$router.push('/user/head-img')
            }
        },
        saveNickName() {
            saveNickName(this.newnick).then(() => {
                this.setNickName(this.newnick)
                this.showNickDialog = false
            }).catch(err => {
                showToast(err)
            })
        },
        updatePushState(item) {
            var period = item.value
            postPushState(period).then((res) => {
                if (!res.success) {
                    showNotify({
                        type: 'warning',
                        message: '订阅/取消订阅失败请重试'
                    })
                    item.select = !item.select
                }
            })
        },
    },
    computed: {
        ...mapState(useUserStore, ['ID', 'VIP', 'nickName', 'userName', 'avatarImg', 'memberEndTime', 'strategyAllList',]),
        headimg() {
            return this.avatarImg ? this.avatarImg : defaultHead
        },
        pushStateDesc() {
            if (!this.pushState) {
                return ''
            }
            if (this.pushState == 'YES') {
                return ''
            }
            if (this.pushState == 'NO15M') {
                return ''
            }
            return ''
        }
        // memberEndTime() {
        //   return this.userName.length >= 15 ? this.userName.substring(0, 5) + '...' + this.userName.substring(this.userName.length - 5) : this.userName
        // }
    },
}
</script>

<style lang="less" scoped>
.my-container {
    // padding: 0 20px;
    // height: calc(100vh - 106px);
    // overflow: auto;
    // overflow-x: hidden;

    height: calc(100vh - 126px);
    padding: 16px;
    overflow-x: hidden;
    overflow-y: auto;
    overflow: overlay;
}

.checkPbox {
    margin-top: 10vh;
    margin-left: 20vw;
    text-align: left;
}

.confirm {
    border: none
}

// 个人中心
.usercenter {
    .userinfo {
        margin-top: 16px;
        display: flex;
        align-items: center;
        justify-content: center;

        .avatar .van-image,
        .avatar img {
            width: 36px;
            height: 36px;
            border-radius: 50%;
        }

        .nickname {
            display: flex;
            align-items: center;

            .button-primary {
                margin: 4px;
            }

            .nickname-text {
                padding: 1px 10px;
                font-weight: 500;
                font-size: 20px;
            }
        }

        .userid-info {
            color: #bebccd;

            .userid {
                padding: 2px 14px;
                z-index: 10;
            }
        }
    }
    .vip-strategy-list {
        color: var(--main-color);
        font-size: 12px;
    }

}
.dialog-set {
    padding: 16px 20px;
}
.dialog-save {
    margin: 20px auto 0;
}


.dialog-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
}
.van-col--8 {
    display: flex;
}
</style>